<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<canvas id="webgl" width="600" height="400" style="width:100%; height:100%;"></canvas>

<script id="vertex-shader-2d" type="notjs">
    attribute vec2 a_position;
    uniform vec2 u_resolution;
    void main(){
        // 从像素坐标转换到0.0到1.0
        vec2 zeroToOne = a_position / u_resolution;
        // 再把 0->1 转换为 0->2
        vec2 zeroToTwo = zeroToOne * 2.0;
        // 再把 0->2 转换为 -1->1(裁剪空间)
        vec2 clipSpace = zeroToTwo - 1.0;

        gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
    }
</script>

<script id="fragment-shader-2d" type="notjs">
    precision mediump float;
    uniform vec4 u_color;
    void main(){
        gl_FragColor = u_color;
    }
</script>

<script src="./utils/webgl-utils.js" type="text/javascript"></script>

<script type="text/javascript">
    function randomInt(range) {
        return Math.floor(Math.random() * range);
    }

    function setRectangle(gl, x, y, width, height) {
        let x1 = x;
        let x2 = x + width;
        let y1 = y;
        let y2 = y + height;
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
            x1, y1,
            x2, y1,
            x1, y2,
            x1, y2,
            x2, y1,
            x2, y2
        ]), gl.STATIC_DRAW);
    }

    let canvas = document.querySelector("#webgl");
    let gl = canvas.getContext("webgl");

    if (!gl) {
        alert("您的浏览器不支持WebGl！");
    }

    let program = createProgramFromScripts(gl, "#vertex-shader-2d", "#fragment-shader-2d");
    let positionAttributeLocation = gl.getAttribLocation(program, "a_position");
    let resolutionUniformLocation = gl.getUniformLocation(program, "u_resolution");
    let colorUniformLocation = gl.getUniformLocation(program, "u_color");
    gl.useProgram(program);

    let positionBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);


    resize(gl.canvas);
    gl.viewport(0, 0, gl.canvas.clientWidth, gl.canvas.clientHeight);
    /*
    * 渲染代码
    * */
    gl.clearColor(0, 0, 0, 0.5);
    gl.clear(gl.COLOR_BUFFER_BIT);


    gl.enableVertexAttribArray(positionAttributeLocation);
    gl.vertexAttribPointer(positionAttributeLocation, 2, gl.FLOAT, false, 0, 0);

    // 设置全局变量的值必须要在使用着色器程序之后
    gl.uniform2f(resolutionUniformLocation, gl.canvas.width, gl.canvas.height);

    for (let i = 0; i < 50; i++) {
        setRectangle(gl, randomInt(300), randomInt(300), randomInt(300), randomInt(300));
        gl.uniform4f(colorUniformLocation, Math.random(), Math.random(), Math.random(), 1);
        gl.drawArrays(gl.TRIANGLES, 0, 6);
    }






</script>
</body>
</html>
